#coding=utf-8
'''
Created on 2015年5月27日
'''
import json
import hashlib
from util_base.exception import UFOException, ParamException
from util_base.common_utils import ComplexEncoder
from common_base.errors import AliveError
from handler_base.base_handler import BaseHandler
from util_base.common_decorators import override
from util_base.logging_utils import Tracker
from common_base.constants import LanguageType



class InternalHandler(BaseHandler):
    '''
    internal handler, receive requests from internal alive systems and distribute them to processors
    '''
    
    is_internal = True
    
    def __init__(self, *args, **kwargs):
        '''
        Constructor
        '''
        
        BaseHandler.__init__(self, *args, **kwargs)
        self.set_header("Content-Type", "application/json")
        self.tracker = Tracker('internalTrack')
        self.sys_logger = Tracker('root')
        
    @override
    def parse_header(self):
        '''
        解析请求头
        '''
        
        # 从header中解析参数
        try:
            self.cmdid = int(self.request.headers.get('cmdId'))
        except:
            raise ParamException('cmdId')
        
        try:
            self.app_version = self.request.headers.get('AppVersion')
        except:
            raise ParamException('AppVersion')

        try: 
            self.timestamp = int(self.request.headers.get('Timestamp'))
        except:
            raise ParamException('Timestamp') 

        try: 
            self.sign_type = self.request.headers.get('SignType')
        except:
            raise ParamException('SignType') 
        
        try: 
            self.request_sign = self.request.headers.get('RequestSign')
        except:
            raise ParamException('RequestSign') 
        
        # 增加校验 
        secretKey = self.application.alive_base_info.get('internal_key', '')
        sign_str = '''AppVersion=%s&Body=%s&SignType=%s&Timestamp=%s&secretKey=%s'''\
                   %(self.app_version, self.request.body.decode('utf-8'), self.sign_type, self.timestamp, secretKey)

        if hashlib.md5(sign_str.encode('utf-8')).hexdigest().upper() != self.request_sign:
            raise ParamException('RequestSign')
    
        
    
    @override
    def parse_body(self):
        
        # json解析 
        try:
            json_body = json.loads(self.request.body.decode('utf-8'))
        except:
            raise UFOException(AliveError.ERROR_COMMON_PARSE_JSON_FAILED)

        # TODO: 过滤非法字符
        
        # 参数校验
        if 'common' not in json_body:
            raise ParamException('common')
        common = json_body.get('common')
        self.common = common

        if 'userId' not in common:
            raise ParamException('userId')
        self.userid = common.get('userId')
        
        if 'release' in common:
            self.release = common.get('release')

        if 'platform' in common:
            self.platform = common.get('platform')

        if 'sessionId' not in common:
            raise ParamException('sessionId')
        self.session_id = common.get('sessionId')

        if 'userKey' not in common:
            raise ParamException('userKey')
        self.user_key = common.get('userKey')

        # 没有指定语言默认为中文
        self.language = common.get('language', LanguageType.CN)

        if 'params' in json_body:
            self.params = json_body.get('params')

        return json_body
    
    @override
    def verify_processor_meta(self, meta):
        '''
        '''
        
        # 协议处理
        if not meta.internal_only and not meta.internal_access:
            # 不支持内部调用的协议
            raise UFOException(AliveError.ERROR_COMMON_PROTOCOL_FOR_EXTERNAL_ONLY)
        
    @override
    def serialize_response(self):
        return json.dumps(self.res, cls=ComplexEncoder)
        

